<?php

if (substr(PHP_VERSION, 0, 1) < '7') {
  die('请使用php7.0以上的版本');
}

use Workerman\Worker;

require_once './Workerman/Autoloader.php';

$worker = new Worker('http://0.0.0.0:9000');

//开启的进程数量
$worker->count = 1;
//此特性需要PHP版本>=7.0
$worker->reusePort = true;

//类的自动加载
spl_autoload_register(function ($classname) {
  $classpath = "./" . $classname . '.php';
  if (file_exists($classpath)) {
    require_once($classpath);
  }
});

//加载api目前下的所有php文件
$d = dir("./api");
while (false !== ($entry = $d->read())) {
  if (!in_array($entry, ['.', '..'], true)) {
    require_once $d->path . '/' . $entry;
  }
}
$d->close();


//进程启动
$worker->onWorkerStart = function ($worker) {
};

$worker->onMessage = function ($connection, $request) {

  $url = $request->uri();

  $idx = strpos($url, '?');
  if (empty($idx)) {
    $idx = strpos($url, '&');
  }

  if (!empty($idx)) {
    $url = substr($url, 0, $idx);
  }

  $routes = array_values(array_filter(explode('/', $url)));

  if (!array_key_exists(0, $routes)) {
    $connection->send("路由错误!");
    return;
  }

  if ($routes[0] === 'favicon.ico') {
    return;
  }

  if (!array_key_exists(1, $routes) || !array_key_exists(2, $routes)) {
    $connection->send("路由错误2!");
    return;
  }

  if (in_array($routes[1], ['base', 'pools'])) {
    $connection->send("控制器不存在：" . $routes[1]);
    return;
  }

  //查看目录是否存在
  $dir =  './' . $routes[0];

  if (!is_dir($dir)) {
    $connection->send("目录不存在：" . $routes[0]);
    return;
  }

  if ($routes[1] === 'pools') {
    $connection->send("控制器不存在：" . $routes[1]);
    return;
  }

  //查看控制器存不存在
  $c = $dir . '/' . $routes[1] . '.php';

  if (!file_exists($c)) {
    $connection->send("控制器不存在：" . $routes[1]);
    return;
  }

  $class_name =  $routes[1];
  //查询连接池是否有该类
  $pools = 'pools';
  if (!array_key_exists($class_name, $pools::$pools)) {
    $model = new $class_name();
    $pools::$pools[$class_name] = $model;
  }

  $model = $pools::$pools[$class_name];

  if (!method_exists($model, $routes[2])) {
    $connection->send("未定义的方法:" . $routes[2]);
    return;
  }

  $method = $routes[2];

  $connection->send($model->$method());
};

// 运行worker
Worker::runAll();
